dofile (getScriptPath() .. "\\..\\processor\\processor.lua")

if not processor.save then


processor.saver_data = {}


function processor:InitSaver(sid, fn)
	if not self.saver_data then self.saver_data = {} end
	if not sid or not fn then return end
	local id = "saver." .. tostring(sid)
	if self.saver_data[id] then
		self.saver_data[id].file = fn
		if self.saver_data[id].hfile then
			self.saver_data[id].hfile:close()
			self.saver_data[id].hfile = nil
		end
	else
		self.saver_data[id] = {file = fn}
		
		self:AddCallback(id)
		
		self:AddHandler(id, function(text, id, qn)
			if not processor.saver_data[id] then return end
			if not processor.saver_data[id].file then return end
			
			if not processor.saver_data[id].hfile then
				processor.saver_data[id].hfile = io.open(processor.saver_data[id].file, "a+")
			end
			if processor.saver_data[id].hfile then
				processor.saver_data[id].hfile:write(text .. "\n")
				processor.saver_data[id].delay = nil
				if processor.saver_data[id].is_shared and qn < 2 then
					processor.saver_data[id].hfile:close()
					processor.saver_data[id].hfile = nil
				else
					processor.saver_data[id].writed = 3
				end
			elseif processor.saver_data[id].delay then
				if not processor:IsDelay(processor.saver_data[id].delay, 3000) then
					return true
				end
			else
				processor.saver_data[id].delay = processor:GetTime()
				return true
			end
		end)
	end
	return self.saver_data[id]
end


function processor:InitSharedSaver(sid, fn)
	local d = self:InitSaver(sid, fn)
	if d then
		d.is_shared = true
	end
	return d
end


function processor:save(...)
	local arg = {...}
	local id
	for i, a in ipairs(arg) do
		if i == 1 then
			id = "saver." .. tostring(a)
		else
			self:PushData(id, a)
		end
	end
end


function processor:CloseSaver(sid)
	local id = "saver." .. tostring(sid)
	if self.saver_data[id] and self.saver_data[id].hfile then
		self.saver_data[id].hfile:close()
		self.saver_data[id].hfile = nil
	end
end


processor:AddTimer(function(t)
	for k, v in pairs(processor.saver_data) do
		if v.hfile then
			if v.writed then
				v.writed = v.writed - 1
				if v.writed > 0 then
					v.hfile:flush()
				else
					v.hfile:close()
					v.hfile = nil
				end
			else
				v.hfile:close()
				v.hfile = nil
			end
		end
	end
end)


processor:AddStop(function(t)
	for k, v in pairs(processor.saver_data) do
		v.file = nil
		if v.hfile then
			v.hfile:close()
		end
	end
	processor.saver_data = {}
end)


end -- of file
